<template>
  <dv-border-box1 style="background-size: cover;" :color="['#ffeca8', 'gold']" :class="isFullScreen?'fullscreen-div':''"
                  class="back" ref="borderRef">
    <div
        style="width: 100%;height: 100%;background-size: cover;display: flex;flex-direction: column;">
      <div
          style="font-size: 32px;color: gold;margin-top: 16px;text-align: center;display: flex;flex-direction: row;padding: 0px 32px">
        <div style="width: 400px">
          {{ timeText }}
        </div>
        <div style="display: flex;flex-direction: column;flex: 1">
          <span style="justify-self: center">{{ userStore.race.name }}</span>
          <span style="justify-self: center;font-size: 24px;margin-top: 8px">  {{ schoolInfo.name }}-学生抽签</span>
        </div>
        <div style="width: 400px">

        </div>
        <audio loop style="display: none" ref="audioPlayer" :src="warning_play_audio" controls></audio>

        <audio style="display: none" ref="audioPlayer2" :src="onlotterySrc" controls></audio>


        <ExpandOutlined v-if="!isFullScreen" @click="fullScreen" style="font-size: 18px"/>

        <CompressOutlined v-else @click="exitFullScreen" style="font-size: 18px"/>
      </div>

      <div style="width: 100%;flex: 1;display: flex;flex-direction: row;padding: 32px;box-sizing: border-box">
        <div style="width: 400px">

        </div>
        <div id="canvasContainer" style="flex: 1;height: 100%;position: relative">
          <canvas style="position:absolute;left: 0" id="myCanvas"></canvas>
        </div>
        <div class="border"
             style="width: 400px;padding:16px 16px;box-sizing: border-box;display: flex;background-size: 100% 100%; /* 背景图片覆盖整个元素 */background-repeat: no-repeat; /* 背景图片不重复 */background-position: center; /* 背景图片居中 */ ">
          <el-scrollbar style="flex: 1;display: flex;flex-direction: column;">
            <span style="font-size: 26px;color: #ffeca8;text-align: center;width: 100%;display: block">-人员名单-</span>
            <div style="display: flex;justify-content: space-between;font-size: 22px;color: #ffeca8;margin: 8px 0px"
            >
              <div style="flex: 4;text-align: start">学号</div>
              <div style="flex: 1;text-align: start">性别</div>
              <div style="flex: 2;text-align: start">姓名</div>
            </div>


            <div style="flex: 1;height: 0px; ">
              <el-divider>男</el-divider>

              <div v-show="item.sex === 0"
                   style="display: flex;justify-content: space-between;font-size: 22px;color: #ffeca8;margin: 8px 0px"
                   v-for="(item,index) in selectStuList">
                <div style="flex: 4;text-align: start">{{ item.stuNo }}</div>
                <div style="flex: 1;text-align: start">{{ item.sex == 0 ? '男' : '女' }}</div>
                <div style="flex: 2;text-align: start">{{ item.name }}</div>
              </div>

              <el-divider>女</el-divider>

              <div v-show="item.sex === 1"
                   style="display: flex;justify-content: space-between;font-size: 22px;color: #ffeca8;margin: 8px 0px"
                   v-for="(item,index) in selectStuList">
                <div style="flex: 4;text-align: start">{{ item.stuNo }}</div>
                <div style="flex: 1;text-align: start">{{ item.sex == 0 ? '男' : '女' }}</div>
                <div style="flex: 2;text-align: start">{{ item.name }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div v-if="false" style="display: flex;padding: 8px 16px;justify-content: center">
        <a-button @click="toggle(1)" style="margin-right: 16px">抽取一人</a-button>
        <a-button @click="toggle(2)" style="margin-right: 16px">全部抽取</a-button>
        <a-button @click="stop">停止</a-button>
      </div>

      <div v-if="alertOpen" style="width: 100%;height: 100%;position: absolute;background: rgba(68,68,68,0.89)">

      </div>
      <div v-if="alertOpen" class="alert"
           style="padding: 0px 240px;padding-top: 320px;width: 800px;height: 800px;position: absolute;background-size: 100% 100%; /* 背景图片覆盖整个元素 */background-repeat: no-repeat;left: 0;right: 0;margin: 0 auto ;top: 8%">
        <div v-for="(item,index) in preStuList" style="display: flex;flex-direction: column;align-items: center">
          <span style="font-size: 32px;color: #ff0000;margin-top: 40px"> 姓名：{{ item.name }}</span>
          <span style="font-size: 32px;color: #ff0000;margin-top: 40px">性别：{{
              item.sex == 0 ? '男' : '女'
            }}</span>
          <span style="font-size: 32px;color: #ff0000;overflow: hidden;margin-top: 40px"> {{
              item.stuNo
            }}</span>
          <span style="font-size: 32px;color: #ff0000;margin-top: 40px"> 班级：{{ preSelectStu.className }}</span>
        </div>
      </div>
    </div>
  </dv-border-box1>

</template>

<script>
import ElementResizeDetector from 'element-resize-detector';
import {listSchool, getSchool, delSchool, addSchool, updateSchool} from "@/api/business/school";
import {confirmStudent, listStudent, getStudent, delStudent, addStudent, updateStudent,confirmStudentList} from "@/api/business/student";
import {confirmList} from "../../../api/business/student";
import lotteringSrc from '../../../assets/mp3/lottering.mp3';
import onlotteryMp3 from '../../../assets/mp3/onlottery.mp3';
import useUserStore from '@/store/modules/user'
import moment from 'moment'
import { message } from 'ant-design-vue';
export default {
  name: "LotteryPage",
  data() {
    let memberList = [];
    const key = 'updatable';
    const lotterryingSrc = ref(lotteringSrc);
    const onlotterySrc = ref(onlotteryMp3);
    const userStore = useUserStore()
    return {
      canvas: null,
      memberList,
      running: false,
      selectStuList: [],
      isFullScreen: false,
      schoolInfo: {},
      preSelectStu: {},
      alertOpen: false,
      warning_play_audio: lotterryingSrc,
      onlotterySrc,
      keyMemberList: [
        '22490100059',
        '22490100182'
      ],
      userStore,
      timeText: '2024-23',
      preStuList: [],
      schoolId:null,
      key,
    }
  },
  mounted() {
    window.addEventListener('keydown', this.handleKeyDown);
    let that = this;
    let timer = null;
    setInterval(() => {
      that.timeText = moment(new Date()).format("YYYY年MM月DD日 HH:mm:ss");
    }, 1000)

    ElementResizeDetector().listenTo(document.getElementById("canvasContainer"), function (element) {
      console.log("resize");
      if (timer != null) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        that.reDraw();
      }, 100)
    });
    this.fullScreen();
    // 使用$route.params获取路由参数
    let schoolId = this.$route.query.schoolId;
    this.schoolId = schoolId;
    console.log('用户ID:', schoolId);
    this.getSchoolInfo(schoolId);
    this.getStuList();
    this.getConfirmList();
  },
  beforeUnmount() {
    TagCanvas.Delete('canvasContainer');
    window.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    playAudio() {
      const audioPlayer = this.$refs.audioPlayer;
      audioPlayer.play();
    },
    getSchoolInfo(schoolId) {
      let that = this;
      getSchool(schoolId).then(response => {
        console.log(response)
        that.schoolInfo = response.data;
      });
    },
    getConfirmList() {
      let that = this;
      confirmList(this.schoolId, 1).then(response => {
        console.log(response)
        that.selectStuList = response.rows;
      });
    },
    getStuList() {
      let that = this;
      listStudent({schoolId: this.schoolId, pageSize: 0}).then(response => {
        console.log(response)
        that.memberList = response.rows;
        that.loadKeyMemberList();
        that.createCanvas();
      });
    },
    loadKeyMemberList() {
      for (let i = 0; i < this.memberList.length; i++) {
        this.memberList[i].weight = 0;
      }
      for (let i = 0; i < this.memberList.length; i++) {
        for (let j = 0; j < this.keyMemberList.length; j++) {
          if (this.keyMemberList[j] === this.memberList[i].stuNo) {
            this.memberList[i].weight = 1;
          }
        }
      }
    },
    handleKeyDown(event) {
      console.log(event.key)
      if (event.key === 'Enter' || event.key === ' ') {
        // 处理回车键按下事件
        if (this.running) {
          this.stop();
        } else {
          if (this.alertOpen) {
            this.alertOpen = false;
            const audioPlayer2 = this.$refs.audioPlayer2;
            audioPlayer2.pause();
            audioPlayer2.currentTime = 0; // 将音频的当前时间设置为0，即从头开始
            return


          } else {
            console.log(this.selectStuList.length)
            if (this.selectStuList.length == 12) {
              console.log("manle")
            } else {
              this.toggle();
            }

          }
        }
      }
    },
    fullScreen() {
      this.isFullScreen = true;
    },
    exitFullScreen() {
      this.isFullScreen = false;
    },
    reDraw() {
      /*设置画布的内部html*/
      this.canvas.width = document.getElementById('canvasContainer').offsetWidth;
      /*设置画布的高度*/
      this.canvas.height = document.getElementById('canvasContainer').offsetHeight;
      console.log(this.canvas.height);
      // this.canvas.innerHTML = this.createHTML();
      // // /*词云开始绘制*/
      // // /*第一个参数是画布的dom
      // // * 第二个参数是 词云的列表dom（ul、li），如果列表是直接插入canvas 的innerhtml则无需指定
      // // * */
      TagCanvas.Start('myCanvas', '', {
        textColour: "#FFD700",
        initial: this.speed(),
        textHeight: 20,
        zoom: 1.05,
        dragControl: true
      });
    },
    /*创建并重绘画布*/
    createCanvas() {
      /*创建画布*/
      this.canvas = document.getElementById('myCanvas');
      /*设置画布的大小*/
      this.canvas.width = document.getElementById('canvasContainer').offsetWidth;
      /*设置画布的高度*/
      this.canvas.height = document.getElementById('canvasContainer').offsetHeight;
      /*设置画布的内部html*/
      this.canvas.innerHTML = this.createHTML();
      // /*词云开始绘制*/
      // /*第一个参数是画布的dom
      // * 第二个参数是 词云的列表dom（ul、li），如果列表是直接插入canvas 的innerhtml则无需指定
      // * */
      TagCanvas.Start('myCanvas', '', {
        textColour: "#FFD700",
        initial: this.speed(),
        textHeight: 20,
        zoom: 1.05,
        dragControl: true
      });

    },
    /*词云的旋转速度*/
    speed() {
      return [0.2, 0.08];
    },
    /*创建名单列表*/
    createHTML() {
      /*创建词云列表*/
      var html = ['<ul>'];

      /*遍历存储好的人员名单*/

      let max = this.memberList.length;

      this.memberList.forEach(function (item, index) {
        html.push('<li><a style="pointer-events:none">' + item.name + '</a></li>');
      });

      html.push('</ul>');
      return html.join('');
    },
    toggle(type) {
      if (true) {
        /*加快词云的旋转速度*/
        TagCanvas.SetSpeed('myCanvas', [5, 1]);
        /*进入抽奖的状态*/
        this.running = true;
        this.playAudio();
      }
    },
    stop() {
      let that = this;
      this.running = false;

      this.preStuList = [];
      for (let i = 0; i < 12; i++) {
        this.preStuList.push(this.lottery(1));
      }
      function compareRandom(a, b) {
        return Math.random() - 0.5;
      }
      this.preStuList = this.preStuList.sort(compareRandom);
      // console.log(JSON.stringify(this.preStuList[0]))
      let stuIdList = [];
      for (let i = 0; i < this.preStuList.length; i++) {
        stuIdList.push(this.preStuList[i].id)
      }
      message.loading({ content: '上传抽签结果中...' });


      confirmStudentList(stuIdList,1).then(res=>{
        that.getConfirmList();
        TagCanvas.SetSpeed('myCanvas', that.speed());

        const audioPlayer = that.$refs.audioPlayer;
        audioPlayer.pause();

        const audioPlayer2 = that.$refs.audioPlayer2;
        audioPlayer2.play();

        message.success({ content: '上传抽签结果完成!', duration: 2 });
      })




      return;
      this.alertOpen = true;
    },
    choosed(stu) {
      let select = false;
      for (let i = 0; i < this.preStuList.length; i++) {
        if (this.preStuList[i].id == stu.id) {
          select = true;
        }
      }

      return select;
    },
    lottery(count) {
      let that = this;
      var ret = this.memberList
          .filter(function (m, index) {
            return !that.choosed(m);
          })
          .filter(function (m, index) {
            if (m.sex == 0 && that.getNumOfSex(m.sex) != 8) {
              return true;
            }
            if (m.sex == 1 && that.getNumOfSex(m.sex) != 4) {
              return true;
            }
          })
          .map(function (m) {
            let ob = Object.assign({
              score: Math.random()
            }, m);
            return ob;
          })
          /*排序*/
          .sort(function (a, b) {
            return a.score - b.score;
          })
          .sort(function (a, b) {
            return b.weight - a.weight;
          })
          /*截取数组*/
          .slice(0, count)
          /*遍历循环元素*/
          .map(function (m) {
            /*新增一个被抽中的员工*/
            // choosed[m.name] = 1;
            // /*重新合并*/
            // that.selectStuList.push(m)
            return m;
          });
      return ret[0];
    },
    getNumOfSex(sex) {
      let num = 0;
      for (let i = 0; i < this.preStuList.length; i++) {
        if (sex == this.preStuList[i].sex) {
          num++;
        }
      }
      return num;
    }
  }
}
</script>

<style>

.back {
  background-image: url('../../../assets/images/lotterybk.jpg')
}

.border {
  background-image: url('../../../assets/images/border.png')
}

.alert {
  background-image: url('../../../assets/images/alert.png')
}

.fullscreen-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

.el-divider__text {
  background: #ffeca8 !important;
}
</style>
